﻿function onLogin() {
    var userName = $('#userName').val();
    if (!userName) {
        alert('请输入用户名!');
        return;
    }

    var password = $('#password').val();
    if (!password) {
        alert('请输入密码!');
        return;
    }

    //password = sha256(password);
    var returnUrl = getQueryString('ReturnUrl');
    var autoLogin = $('#autoLogin').prop('checked');
    $.ajax({
        type: 'POST',
        url: "/api/account/login",
        dataType: 'json',
        contentType: 'application/ json',
        data: JSON.stringify({ userName, password, autoLogin, returnUrl }),
        success: data => {
            if (data && data.status == "ok") {
                if (data.userInfo) {
                    data.userInfo.userName = userName;
                    localCache.global.set("user", data.userInfo);
                }

                location.href = "/Home/Index";
            } else {
                alert(data || data.message);
            }
        },
        error: err => {
            console.log(err);
        }
    });
}

function getQueryString(key) {
    var queryString = location.href.match(new RegExp("[\?\&][^\?\&]+=[^\?\&]+", "g"));
    if (queryString && queryString instanceof Array && queryString.length > 0) {
        for (var i = 0; i < queryString.length; i++) {
            var cur = queryString[i];
            cur = cur.substring(1);
            if (cur) {
                index = cur.indexOf('=');
                if (index > 0) {
                    var name = cur.substring(0, index);
                    if (name == key) {
                        return cur.substring(index + 1, cur.length);
                    }
                }
            }
        }
    }

    return undefined;
};